package com.bbz.core.nio.chapter1;

import cn.hutool.extra.servlet.multipart.UploadFile;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 该组件实现了服务器对从客户端接收的数据的处理，即它的业务逻辑
 */
@ChannelHandler.Sharable  //标示一个Channel-Handler 可以被多个Channel 安全地共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
  private static final   AtomicInteger atomicI=new AtomicInteger();
  int index=0;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        index= atomicI.incrementAndGet();
        System.out.println(index+"Server received: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);//将接收到的消息写给发送者，而不冲刷出战消息
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        //将未解决的消息冲刷到远程节点，并且关闭该channel
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);
    }

    //如果不捕获异常，ChannelHandler会将异常发送到下一个ChannelHandler
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }
}
